using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Collections.Generic;
using System.Linq;
using Microsoft.Phone.Controls;
using System.IO;
using System.Collections;



using System.Text;
using System.Diagnostics;
using System.Net.Sockets;

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO.IsolatedStorage;
using Newtonsoft.Json.Linq;
using Qplus.Infrastructure;
namespace Qplus.Commands
{

    /**
     * 
     * http 命令
     * 
     */
    public abstract class HttpCommand {
	    /**
	     * 命令名字
	     */
	    protected String command;
	    /**
	     * 命令参数
	     */
        protected Dictionary<string, object> param;

        protected Dictionary<string, string> headers;
        protected List<object> headerList;

        protected Stream responseStream;
	
	    private string context;

        protected event EventHandler<MessageReceivedFromServer> MessageReceivedFromHttpServer;
        public MessageReceivedFromServer msgfromS;

        public HttpCommand(String command)
        {
		    param = new Dictionary<string, object>();
            headers = new Dictionary<string, string>();
            headerList = new List<object>();
		    this.command = command;
	    }

	    public String getCommand() {
		    return command;
	    }

	    public void setCommand(String command) {
		    this.command = command;
	    }

	    public Dictionary<string, object> getParams() {
		    return param;
	    }
	
	    protected void addParams(String name, Object value){
            param.Add(name, value);
	    }
	
	    protected void addParams(String name, String value){
		    param.Add(name, value);
	    }
	
	    protected void addParams(String name, int value){
		   param.Add(name, value);
	    }
	
	    protected void addParams(String name, long value){
		    param.Add(name, value);
	    }
	
	    protected void addHeader(String name, String value){
            headers.Add(name, value);
	    }


        protected void addHeaderList()
        {
            WebHeaderCollection Header = new WebHeaderCollection();
            foreach (KeyValuePair<string, string> entry in headers)
            {
                Header[entry.Key] = entry.Value;
            }

            headerList.Add(Header);
        }

	
	    public void setEntity(Stream repStream){
            this.responseStream = repStream;
	    }

        public Stream getEntity()
        {
            return responseStream;
	    }
	
	    public String getUrl(){
		    StringBuilder url = new StringBuilder();
		    url = url.Append("/" + command + "?");
            foreach( KeyValuePair<string,object> entry in param)
            {
                url.Append(entry.Key + "=" + entry.Value + "&");
            }
		    return url.ToString();
	    }


        public String getPara()
        {
            StringBuilder para = new StringBuilder();
            //para = para.Append("/" + command + "?");
            foreach (KeyValuePair<string, object> entry in param)
            {
                para.Append(entry.Key + "=" + entry.Value + "&");
            }
            return para.ToString();
        }
	
	    
	    public override String ToString() {
		    return getUrl();
	    }

        public List<object> getHeaders()
        {
            return headerList;
	    }

        public void setHeaders(List<object> headers)
        {
            this.headerList = headers;
	    }
	
	    public HttpTask execute(String url, HttpInputStreamProcessor processor){
		    HttpTask task = new HttpTask(url + command , this, processor, getPara());
            task.DownloadCompleted += new HttpTask.DownloadCompletedHandler(proxy_DownloadCompleted);
            task.DownloadAsync();
		    return task;
	    }
        
        void proxy_DownloadCompleted(object sender, DownloadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                //Process the result... 
                string data = System.Text.UTF8Encoding.UTF8.GetString(e.Data, 0, e.Data.Length);

                Debug.WriteLine(data);

                ProcessIncomingMessage(e.Data);

                #region save data
                //JObject jo = null;
                //JArray ja = null;
                //try
                //{
                //    jo = JObject.Parse(e.Result);
                //}
                //catch { }
                //try
                //{
                //    ja = JArray.Parse(e.Result);
                //}
                //catch { }
                //UI.UIData uidata = UI.UIData.Instance;
                //if (null != ja)
                //{
                //    UI.chatList chatlist = UI.chatList.getInstance();
                //}
                //if (null != jo)
                //{
                //    if (null != jo["userList"])
                //    {
                //        UI.userList userlist = UI.userList.getInstance();
                //        userlist.update(jo);
                //        uidata.userList = userlist;
                //    }
                //    else if (null != jo["roomList"])
                //    {
                //        UI.roomList roomlist = UI.roomList.getInstance();
                //        roomlist.update(jo);
                //        uidata.roomList = roomlist;
                //    }
                //    else if (null != jo)
                //    {
                //        UI.userInfo userinfo = UI.userInfo.getInstance();
                //        userinfo.update(jo);
                //        uidata.userInfo = userinfo;
                //    }
                //}
                #endregion
#region TEST
                //try
                //{
                //    JArray jsona = JArray.Parse(e.Result);
                //    //var j = jsona.First.ToObject(typeof(JObject));
                //    var j = jsona.First;
                //    while (null != j)
                //    {
                //        j = j.Next;
                //        //JObject jo = (JObject)j.ToObject(typeof(UI.chatList));
                //        JObject jo1 = (JObject)j;
                //        Qplus.UI.chatList clist = new UI.chatList();
                //        {
                //            clist.peerType = (int)j["perType"];
                //            clist.peerID = (int)j["peerID"];
                //            clist.peerName = (string)j["peerName"];
                //            clist.peerLevel = (int)j["peerLevel"];
                //            clist.headType = (int)j["headType"];
                //            clist.headValue = (string)j["headValue"];
                //        };
                //        Debug.WriteLine(clist);
                //        Debug.WriteLine(clist);
                //        Debug.WriteLine(clist);
                //        Debug.WriteLine(clist);
                //        Debug.WriteLine(clist);
                //        Debug.WriteLine(clist);
                //        Debug.WriteLine(clist);
                //    }
                //}
                //catch (Exception e1)
                //{
                //    Debug.WriteLine(e1.Message);
                //}
                //try
                //{
                //    JObject json = JObject.Parse(e.Result);
                //}
                //catch { }
                //try
                //{
                //    var mStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
                //    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Qplus.UI.HttpData));
                //    Qplus.UI.HttpData newList = (Qplus.UI.HttpData)serializer.ReadObject(mStream);
                //    //List localData;
                //    Qplus.UI.user[] userList;
                //    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
                //    //settings.TryGetValue<List>("localData", out localData);
                //    //if (null == localData || null == localData.userList )
                //    //{
                //    //    settings["userList"] = "userList";
                //    //    settings.Add("userList", newList.userList);//["userList"] = userList;
                //    //    settings.TryGetValue<List>("userList", out localData);
                //    //    if (null == localData)
                //    //    {
                //    //        Debug.WriteLine("userList is null");
                //    //    }
                //    //}
                //    //if (null == localData || null == localData.roomList)
                //    //{
                //    //    settings["roomList"] = "roomList";
                //    //    settings.Add("roomList", newList.roomList);
                //    //    settings.TryGetValue<List>("userList", out localData);
                //    //    if (null == localData)
                //    //    {
                //    //        Debug.WriteLine("userList is null");
                //    //    }
                //    //}
                //    settings.TryGetValue<Qplus.UI.user[]>("userList", out userList);
                //    if (null == userList && null != newList.userList)
                //    {
                //        settings.Add("userList", newList.userList);//["userList"] = userList;
                //        settings.TryGetValue<Qplus.UI.user[]>("userList", out userList);
                //        if (null == userList)
                //        {
                //            Debug.WriteLine("userList is null");
                //        }
                //    }
                //    Qplus.UI.room[] roomList;
                //    settings.TryGetValue<Qplus.UI.room[]>("roomList", out roomList);
                //    if (null == roomList && null != newList.roomList)
                //    {
                //        settings.Add("roomList", newList.roomList);//["userList"] = userList;
                //        settings.TryGetValue<Qplus.UI.room[]>("roomList", out roomList);
                //        if (null == roomList)
                //        {
                //            Debug.WriteLine("roomList is null");
                //        }
                //    }

                //    Qplus.UI.userInfo userInfo;
                //    settings.TryGetValue<Qplus.UI.userInfo>("userInfo", out userInfo);
                //    if (null == userInfo && null != newList.user)
                //    {
                //        settings.Add("userInfo", newList.user);//["userList"] = userList;
                //        settings.TryGetValue<Qplus.UI.userInfo>("roomList", out userInfo);
                //        if (null == userInfo)
                //        {
                //            Debug.WriteLine("userInfo is null");
                //        }
                //    }

                //    Debug.WriteLine("");
                //}
                //catch { }
                //List friendList;
                //System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<List>("userList", out friendList);
                //l2cInfo l2clocal;
                //System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<l2cInfo>("l2cInfo", out l2clocal);
                //if (null != friendList)
                //{
                //    Qplus.Commands.GetResCommand command_GetRes = new Qplus.Commands.GetResCommand(
                //        l2clocal.UserID.ToString(),//friendList.userList[0].userID.ToString(),
                //        System.Text.Encoding.UTF8.GetString(l2clocal.Key,0,l2clocal.Key.Length)); //friendList.userList[0].headValue);
                //    //command_GetRes.set(friendList.userList[0].headValue)
                //    command_GetRes.execute(l2clocal.UpgradeURL);
                //}
#endregion
                #region TEST
                //反序列化，得到Currency类实例

                //var mStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
                //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(userList));
                //userList readuserList = (userList)serializer.ReadObject(mStream);
                //string userID = readuserList.user.userID.ToString();
                //string userName = readuserList.user.userName.ToString();
                //string userLevel = readuserList.user.userLevel.ToString();
                //string headType = readuserList.user.headType.ToString();
                //string headValue = readuserList.user.headValue.ToString();
                                //string  = readuserList.result

                //context = data;
                //IsolatedStorageSettings.ApplicationSettings["result"] = context;
                //string bb;
                //IsolatedStorageSettings.ApplicationSettings.TryGetValue<string>("result", out bb);
                //IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication();
                //if (isofile.FileExists("/data"))
                //    isofile.DeleteFile("/data");
                //StreamWriter sw = new StreamWriter(isofile.CreateFile("/data.txt"), System.Text.Encoding.UTF8);
                //sw.WriteLine("Some data from isolated storage");
                //sw.Close();
                //sw.Dispose();
                //isofile.Dispose();
                #endregion
            }
        }

	    public string getContext() {
		    return context;
	    }

	    public void setContext(string context) {
		    this.context = context;
	    }
        private void ProcessIncomingMessage(byte[] ReceivedMessage)
        {
            // Future hook for handling the message in somewhere else.
            // It's most probably wise to put the parsing logic in some other class.
            if (MessageReceivedFromHttpServer != null)
                MessageReceivedFromHttpServer(this, new MessageReceivedFromServer(ReceivedMessage));
        }
    }
}
